﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Vit.Web.Models;

namespace Vit.AdminModule.Areas.Admin.Providers
{
    public class SqlRelationProvider : Vit.Web.Providers.IRelationProvider
    {
        private WebProvidersDb db = new WebProvidersDb();
        
        #region IRelationProvider Members

        public IEnumerable<string> GetRelationTypes()
        {
            return db.ObjectRelations.Select(o => o.RelationType).Distinct();
        }

        public IQueryable<string> GetRelationObjectIds(string objectType, string objectId, string targetType, string relationType)
        {
            var query1 = from o in db.ObjectRelations
                        where o.Object1Type == objectType && o.Object1ID == objectId && o.Object2Type == targetType
                        select o;
            var query2 = from o in db.ObjectRelations
                         where o.Object2Type == objectType && o.Object2ID == objectId && o.Object1Type == targetType
                         select o;

            if (!string.IsNullOrWhiteSpace(relationType))
            {
                query1 = query1.Where(o => o.RelationType.Contains(relationType));
                query2 = query2.Where(o => o.RelationType.Contains(relationType));
            }

            var query = query1.Select(o => o.Object2ID).Union(query2.Select(o => o.Object1ID));
            return query;
        }

        public void AddRelations(string object1Type, string object1Id, string object2Type, string object2Id, string relationType)
        {
            var relation = db.ObjectRelations.FirstOrDefault(o => o.Object1Type == object1Type && o.Object1ID == object1Id
                && o.Object2Type == object2Type && o.Object2ID == object2Id);
            if (relation != null)
            {
                if (relation.RelationType.Contains(relationType) == false)
                {
                    relation.RelationType += relationType + ",";
                    db.SaveChanges();
                }
            }
            else
            {
                relation = new ObjectRelation()
                {
                    Object1Type = object1Type,
                    Object1ID = object1Id,
                    Object2Type = object2Type,
                    Object2ID = object2Id,
                    RelationType = relationType + ","
                };
                db.ObjectRelations.Add(relation);
                db.SaveChanges();
            }
        }

        #endregion

        #region IProvider Members

        public string Name
        {
            get { return "SqlRelationProvider"; }
        }

        #endregion
    }
}